package com.alienlab.finder.service.impl;

import com.alienlab.finder.domain.AppUser;
import com.alienlab.finder.repository.AppUserRepository;
import com.alienlab.finder.service.RelationshipService;
import com.alienlab.finder.domain.Relationship;
import com.alienlab.finder.repository.RelationshipRepository;
import com.alienlab.finder.service.dto.RelationshipDTO;
import com.alienlab.finder.service.dto.UserState;
import com.alienlab.finder.service.dto.globalData;
import com.alienlab.finder.web.websocket.WebSocketServer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Service Implementation for managing Relationship.
 */
@Service
@Transactional
public class RelationshipServiceImpl implements RelationshipService {

    private final Logger log = LoggerFactory.getLogger(RelationshipServiceImpl.class);

    private final RelationshipRepository relationshipRepository;
    private final AppUserRepository appUserRepository;

    public RelationshipServiceImpl(AppUserRepository appUserRepository,RelationshipRepository relationshipRepository) {
        this.relationshipRepository = relationshipRepository;
        this.appUserRepository =appUserRepository;
    }

    /**
     * Save a relationship.
     *
     * @param relationship the entity to save
     * @return the persisted entity
     */
    @Override
    public Relationship save(Relationship relationship) {
        log.debug("Request to save Relationship : {}", relationship);
        return relationshipRepository.save(relationship);
    }

    /**
     * Get all the relationships.
     *
     * @param pageable the pagination information
     * @return the list of entities
     */
    @Override
    @Transactional(readOnly = true)
    public Page<Relationship> findAll(Pageable pageable) {
        log.debug("Request to get all Relationships");
        return relationshipRepository.findAll(pageable);
    }


    /**
     * Get one relationship by id.
     *
     * @param id the id of the entity
     * @return the entity
     */
    @Override
    @Transactional(readOnly = true)
    public Optional<Relationship> findOne(Long id) {
        log.debug("Request to get Relationship : {}", id);
        return relationshipRepository.findById(id);
    }

    /**
     * Delete the relationship by id.
     *
     * @param id the id of the entity
     */
    @Override
    public void delete(Long id) {
        log.debug("Request to delete Relationship : {}", id);
        relationshipRepository.deleteById(id);
    }

    @Override
    public Relationship creatRelation(String main_open_id, String second_open_id) throws Exception {
        AppUser main_appUser = appUserRepository.findByOpenId(main_open_id);
        if (main_appUser==null){
            throw new Exception("未查找到opden_id为:"+main_open_id+"的用户");
        }
        AppUser second_appUser = appUserRepository.findByOpenId(main_open_id);
        if (second_appUser==null){
            throw new Exception("未查找到opden_id为:"+second_open_id+"的用户");
        }
//        List<Relationship> relationshiplist = relationshipRepository.findBySecondUserOpenId(second_open_id);
//        //提醒通过分享注册小程序的人
//        if (relationshiplist.size()>=1){
//            WebSocketServer.SendMessage(globalData.websocketmap.get(second_open_id.toLowerCase()),"您已与其他用户建立监控关系，请解除绑定后再试!");
//        }
        Relationship old_relationship = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(main_open_id, second_open_id);
        Relationship relationship =new Relationship();
        if (old_relationship==null){
            relationship.setMainUserOpenId(main_open_id);
            relationship.setSecondUserOpenId(second_open_id);
            relationship.setRelation("0");
            relationship.setDistanceSize("200");
            relationship =  relationshipRepository.save(relationship);
        }
        Relationship old_relationship2 = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId( second_open_id,main_open_id);
        if (old_relationship2==null){
            Relationship relationship2 =new Relationship();
            relationship2.setMainUserOpenId(second_open_id);
            relationship2.setSecondUserOpenId(main_open_id);
            relationship2.setRelation("1");
            relationship2.setDistanceSize("");
            relationship2 =  relationshipRepository.save(relationship2);

        }

        return relationship;
    }

    @Override
    public Relationship updateRelation(String main_open_id, String second_open_id, String relation, String distance, String nickname) throws Exception {
        AppUser main_appUser = appUserRepository.findByOpenId(main_open_id);
        if (main_appUser==null){
            throw new Exception("未查找到opden_id为:"+main_open_id+"的用户");
        }
        AppUser second_appUser = appUserRepository.findByOpenId(second_open_id);
        if (second_appUser==null){
            throw new Exception("未查找到opden_id为:"+second_open_id+"的用户");
        }
        Relationship relationship = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(main_open_id, second_open_id);
        if (relationship!=null){

            relationship.setRelation(relation);
            relationship.setDistanceSize(distance);
            relationship.setNickname(nickname);
            relationship = relationshipRepository.save(relationship);

//            Relationship second_relationship = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(second_open_id,main_open_id);
//            if (second_relationship != null) {
//                if ("0".equals(relation)){
//                    second_relationship.setRelation("1");
//                }else{
//                    second_relationship.setRelation("0");
//                }
//                second_relationship = relationshipRepository.save(second_relationship);
//            }

            return  relationship;
        }else {
            throw new Exception("未查找到main_opden_id为:"+main_open_id+",second_open_id为:"+second_open_id+"的关系信息");
        }



    }

    @Override
    public void deleteRelation(String main_open_id, String second_open_id) throws Exception {
        AppUser main_appUser = appUserRepository.findByOpenId(main_open_id);
        if (main_appUser==null){
            try {
                throw new Exception("未查找到opden_id为:"+main_open_id+"的用户");
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        AppUser second_appUser = appUserRepository.findByOpenId(main_open_id);
        if (second_appUser==null){
            throw new Exception("未查找到opden_id为:"+second_open_id+"的用户");
        }
        Relationship first_relationship = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(main_open_id, second_open_id);
        relationshipRepository.delete(first_relationship);
        Relationship second_relationship = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(second_open_id, main_open_id);
        relationshipRepository.delete(second_relationship);

    }

    @Override
    public List<RelationshipDTO> findRelationsByMainopenid(String main_open_id) {
        List<RelationshipDTO> relationshipDTOlist = new ArrayList<>();
        List<Relationship> relationshipList = relationshipRepository.findByMainUserOpenId(main_open_id);
        if (relationshipList.size()>0){
            for (int i = 0; i < relationshipList.size(); i++) {
                RelationshipDTO relationshipDTO = new RelationshipDTO();
                String headimage = appUserRepository.findByOpenId(relationshipList.get(i).getSecondUserOpenId()).getHeadimage();
                relationshipDTO.setHeadImage(headimage);
                if ( "".equals(relationshipList.get(i).getNickname())||relationshipList.get(i).getNickname()== null) {
                    relationshipDTO.setUserName(appUserRepository.findByOpenId(relationshipList.get(i).getSecondUserOpenId()).getWechatname());
                }else {
                    relationshipDTO.setUserName(relationshipList.get(i).getNickname());
                }
                relationshipDTO.setRelationship(relationshipList.get(i));
                relationshipDTOlist.add(relationshipDTO);
            }


        }


        return relationshipDTOlist;
    }

    @Override
    public List<UserState> getOnlineState(String main_open_id) {
        List<UserState> userStateList = new ArrayList<>();
        List<Relationship> relationshipList = relationshipRepository.findByMainUserOpenIdAndRelation(main_open_id,"0");
        if (relationshipList.size()==0){
            return userStateList;
        }else {
            for (int i=0;i<relationshipList.size();i++){
                UserState userState = new UserState();
                String open_id = relationshipList.get(i).getSecondUserOpenId();
                userState.setOpenId(open_id);
                if ("".equals(relationshipList.get(i).getNickname()) || relationshipList.get(i).getNickname()==null){
                    userState.setNickName(appUserRepository.findByOpenId(open_id).getWechatname());
                }else {
                    userState.setNickName(relationshipList.get(i).getNickname());
                }
                if (globalData.websocketmap.get(open_id.toLowerCase())==null){
                    userState.setFlag("0");
                }else{
                    userState.setFlag("1");
                }
                userState.setHeadImage(appUserRepository.findByOpenId(open_id).getHeadimage());

                userStateList.add(userState);

            }
            return userStateList;

        }


    }

    @Override
    public void sendOnlineStateRequset(String second_open_id) throws Exception {
        AppUser main_appUser = appUserRepository.findByOpenId(second_open_id);
        if (main_appUser==null){
            throw new Exception("未查找到opden_id为:"+second_open_id+"的用户");
        }
        List<Relationship> relationshiplist = relationshipRepository.findBySecondUserOpenId(second_open_id);
        if (relationshiplist.size()==0){
            return;
        }
        String main_open_id = relationshiplist.get(0).getMainUserOpenId();
        if (globalData.websocketmap.get(main_open_id.toLowerCase())==null){
            return;
        }else {
            WebSocketServer.SendMessage(globalData.websocketmap.get(main_open_id.toLowerCase()),"被监控人上/下线");
        }

    }

    @Override
    public Relationship getRelation(String main_open_id, String second_open_id) {

        Relationship relationship = relationshipRepository.findByMainUserOpenIdAndAndSecondUserOpenId(main_open_id, second_open_id);

        return relationship;
    }
}
